import axios from 'axios'
import router from '/@router/index'
import { getCache, setCache } from '/@utils/tools.js'
console.log(router);
const settings = {
    // baseURL: 'http://admin.anquan119.net',
    baseURL: 'http://admin.anquan119.net',
    timeout: 50 * 100,
    withCredentials: true
}

const request = axios.create({
    baseURL: settings.baseURL,
    timeout: settings.timeout,
    withCredentials: settings.withCredentials,
})

// 添加请求拦截器
request.interceptors.request.use(config => {
    // 在发送请求之前做某事，比如说 设置token
    if (getCache('token')) {
        config.headers.Authorization = getCache('token')
    }
    return config;
}, error => {
    // 请求错误时做些事
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(response => {
    const res = response.data;
    if (res.data && res.data.token) {
        setCache('token', res.data.token)
    }
    // token过期时退回登录页
    if (res.code == 102) {
        router.push('/login')
    }
    // 如果返回的状态不是200 就主动报错
    // if (res.state != 200) {
    //     return Promise.reject(res.message || 'error')
    // }
    return response;
}, error => {
    return Promise.reject(error.response.data); // 返回接口返回的错误信息
})

export default request